package com.zenithmind.classroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.classroom.mapper.CourseChapterMapper;
import com.zenithmind.classroom.pojo.dto.ChapterCreateDTO;
import com.zenithmind.classroom.pojo.dto.ChapterUpdateDTO;
import com.zenithmind.classroom.pojo.dto.ChapterQueryDTO;
import com.zenithmind.classroom.pojo.domain.CourseChapter;
import com.zenithmind.classroom.pojo.vo.ChapterVO;
import com.zenithmind.classroom.service.CourseChapterService;
import com.zenithmind.common.result.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程章节服务实现类
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseChapterServiceImpl extends ServiceImpl<CourseChapterMapper, CourseChapter> implements CourseChapterService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChapterVO createChapter(ChapterCreateDTO createDTO) {
        log.info("创建章节: {}", createDTO.getTitle());
        
        CourseChapter chapter = new CourseChapter();
        BeanUtils.copyProperties(createDTO, chapter);
        
        // 设置排序值
        if (chapter.getSortOrder() == null) {
            Integer maxSortOrder = baseMapper.getMaxSortOrder(createDTO.getCourseId());
            chapter.setSortOrder(maxSortOrder + 1);
        }
        
        chapter.setCreateTime(LocalDateTime.now());
        chapter.setUpdateTime(LocalDateTime.now());
        
        save(chapter);
        
        return convertToVO(chapter);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateChapter(String id, ChapterUpdateDTO updateDTO) {
        log.info("更新章节: {}", id);
        
        CourseChapter chapter = getById(id);
        if (chapter == null) {
            throw new RuntimeException("章节不存在");
        }
        
        BeanUtils.copyProperties(updateDTO, chapter);
        chapter.setUpdateTime(LocalDateTime.now());
        
        return updateById(chapter);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteChapter(String id) {
        log.info("删除章节: {}", id);
        
        CourseChapter chapter = getById(id);
        if (chapter == null) {
            throw new RuntimeException("章节不存在");
        }
        
        // 软删除
        chapter.setIsDeleted(1);
        chapter.setUpdateTime(LocalDateTime.now());
        
        return updateById(chapter);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean publishChapter(String id) {
        log.info("发布章节: {}", id);
        
        CourseChapter chapter = getById(id);
        if (chapter == null) {
            throw new RuntimeException("章节不存在");
        }
        
        // TODO: 实现发布逻辑
        // chapter.setStatus(1); // 已发布
        // chapter.setPublishTime(LocalDateTime.now());
        chapter.setUpdateTime(LocalDateTime.now());
        
        return updateById(chapter);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unpublishChapter(String id) {
        log.info("下架章节: {}", id);
        
        CourseChapter chapter = getById(id);
        if (chapter == null) {
            throw new RuntimeException("章节不存在");
        }
        
        chapter.setStatus(2); // 已下架
        chapter.setUpdateTime(LocalDateTime.now());
        
        return updateById(chapter);
    }

    @Override
    public List<ChapterVO> getCourseChapters(String courseId, String userId, Boolean includeUnpublished) {
        log.info("获取课程章节列表: courseId={}, userId={}", courseId, userId);
        
        return baseMapper.selectCourseChaptersWithProgress(courseId, userId, includeUnpublished);
    }

    @Override
    public ChapterVO getChapterDetail(String id, String userId) {
        log.info("获取章节详情: id={}, userId={}", id, userId);
        
        return baseMapper.selectChapterDetailWithProgress(id, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean reorderChapters(String courseId, List<String> chapterIds) {
        log.info("调整章节顺序: courseId={}", courseId);
        
        return baseMapper.batchUpdateChapterOrder(chapterIds, courseId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean moveChapter(String id, String targetCourseId, Integer sortOrder) {
        log.info("移动章节: id={}, targetCourseId={}", id, targetCourseId);
        
        CourseChapter chapter = getById(id);
        if (chapter == null) {
            throw new RuntimeException("章节不存在");
        }
        
        chapter.setCourseId(targetCourseId);
        chapter.setSortOrder(sortOrder);
        chapter.setUpdateTime(LocalDateTime.now());
        
        return updateById(chapter);
    }

    @Override
    public ChapterVO copyChapter(String id, String targetCourseId, String title) {
        log.info("复制章节: id={}, targetCourseId={}", id, targetCourseId);
        
        String newChapterId = baseMapper.copyChapter(id, targetCourseId, title, null);
        CourseChapter newChapter = getById(newChapterId);
        
        return convertToVO(newChapter);
    }

    @Override
    public Object getChapterStatistics(String id) {
        log.info("获取章节统计: {}", id);
        
        // TODO: 实现章节统计逻辑
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateChapterStatistics(String id) {
        log.info("更新章节统计: {}", id);
        
        return baseMapper.updateChapterStatistics(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchImportChapters(List<ChapterCreateDTO> chapters) {
        log.info("批量导入章节: {}", chapters.size());
        
        int count = 0;
        for (ChapterCreateDTO createDTO : chapters) {
            try {
                createChapter(createDTO);
                count++;
            } catch (Exception e) {
                log.error("导入章节失败: {}", createDTO.getTitle(), e);
            }
        }
        
        return count;
    }

    @Override
    public List<ChapterVO> exportChapters(List<String> chapterIds) {
        log.info("导出章节: {}", chapterIds);

        LambdaQueryWrapper<CourseChapter> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CourseChapter::getId, chapterIds)
                .eq(CourseChapter::getIsDeleted, 0);

        List<CourseChapter> chapters = list(wrapper);
        return chapters.stream().map(this::convertToVO).toList();
    }

    @Override
    public List<ChapterVO> getCourseChapters(String courseId, Boolean includeUnpublished) {
        log.info("获取课程章节列表: courseId={}, includeUnpublished={}", courseId, includeUnpublished);

        LambdaQueryWrapper<CourseChapter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseChapter::getCourseId, courseId)
                .eq(CourseChapter::getIsDeleted, 0);

        if (!includeUnpublished) {
            wrapper.eq(CourseChapter::getIsPublished, 1);
        }

        wrapper.orderByAsc(CourseChapter::getSortOrder);

        List<CourseChapter> chapters = list(wrapper);
        return chapters.stream().map(this::convertToVO).toList();
    }

    @Override
    public Integer getChapterProgress(String chapterId, String userId) {
        log.info("获取章节学习进度: chapterId={}, userId={}", chapterId, userId);

        // TODO: 实现章节学习进度计算
        // 这里需要查询该章节下所有课时的学习进度，计算平均值
        return 0;
    }

    @Override
    public Integer batchCreateChapters(List<ChapterCreateDTO> chapters) {
        log.info("批量创建章节: {}", chapters.size());

        int count = 0;
        for (ChapterCreateDTO createDTO : chapters) {
            try {
                createChapter(createDTO);
                count++;
            } catch (Exception e) {
                log.error("创建章节失败: {}", createDTO.getTitle(), e);
            }
        }

        return count;
    }

    @Override
    public PageResult<ChapterVO> getChapterPage(ChapterQueryDTO queryDTO) {
        log.info("分页查询章节: {}", queryDTO);
        
        // 创建分页对象
        Page<CourseChapter> page = queryDTO.toPage();
        
        // 构建查询条件
        LambdaQueryWrapper<CourseChapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(queryDTO.getCourseId()), CourseChapter::getCourseId, queryDTO.getCourseId())
                    .like(StringUtils.hasText(queryDTO.getTitle()), CourseChapter::getTitle, queryDTO.getTitle())
                    .eq(queryDTO.getStatus() != null, CourseChapter::getStatus, queryDTO.getStatus())
                    .orderByAsc(CourseChapter::getSortOrder)
                    .orderByDesc(CourseChapter::getCreateTime);
        
        // 执行分页查询
        Page<CourseChapter> chapterPage = page(page, queryWrapper);
        
        // 转换为VO对象
        List<ChapterVO> chapterVOList = chapterPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 返回分页结果
        return new PageResult<>(chapterVOList, chapterPage.getTotal(), chapterPage.getCurrent(), chapterPage.getSize());
    }

    /**
     * 转换为VO
     */
    private ChapterVO convertToVO(CourseChapter chapter) {
        ChapterVO vo = new ChapterVO();
        BeanUtils.copyProperties(chapter, vo);
        
        // 设置状态名称
        vo.setStatusName(getStatusName(chapter.getStatus()));
        vo.setTypeName(getTypeName(chapter.getType()));
        
        // TODO: 补充其他字段转换
        
        return vo;
    }

    private String getStatusName(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "草稿";
            case 1: return "已发布";
            case 2: return "已下架";
            default: return "未知";
        }
    }

    private String getTypeName(Integer type) {
        if (type == null) return "未知";
        switch (type) {
            case 1: return "普通章节";
            case 2: return "实践章节";
            case 3: return "测试章节";
            default: return "未知";
        }
    }
}
